<template>
  <a-modal
    v-model:visible="visible"
    :title="printTitle ? printTitle : '标签打印'"
    width="100%"
    wrap-class-name="tn-model-full-scroll label-print-modal"
    ok-text="开始打印"
    :mask-closable="false"
    :keyboard="false"
    @ok="print"
  >
    <a-space v-if="visible">
      <div v-for="item in labelList" :key="item.labelId">
        <LabelItem v-if="designData" :info="item" :design-data="designData" />
      </div>
    </a-space>
    <template #footer>
      <a-button plian @click="cancel">取消</a-button>
      <a-button v-if="!preview" type="primary" @click="print">开始打印</a-button>
    </template>
  </a-modal>
</template>

<script lang="ts" setup>
import { message, Modal } from 'ant-design-vue'
import { ref } from 'vue'
import { getLodop } from '../../../utils/LodopFuncs.js'
import LabelItem from './labelItem.vue'
import { updateLabelPrintCount } from '@@/api/label/index'
import { setBusinessElementText, setTestBusinessTest } from '../form'
import { setNewelement } from '../mm2px'

const props = defineProps<{
  moduleType?: number // 模块类型 1-模板管理 2-配置管理 3-项目端
  printTitle?: string // title
  customPrintTotalFn?: Function
}>()
const visible = ref(false)
const labelList = ref<any[]>([])
const designData = ref<any>('')

const preview = ref<boolean>(false)
function show(labels, _designData, _preview?) {
  if (!_designData) {
    message.error('标签未设计，请先设计标签后再打印')
    return
  }
  visible.value = true
  labelList.value = labels || []
  designData.value = _designData
  preview.value = _preview
}
const cancel = () => {
  visible.value = false
}

const emits = defineEmits(['printSuccess'])
function print() {
  if (!designData.value) {
    return
  }
  let { canvas, elements } = JSON.parse(designData.value)
  if (canvas.childCanvas1) {
    elements = setNewelement(elements)
  }
  // 打印
  // 腕带 宽27 高80 上30
  const offsetTop = canvas.offsetTop || 0
  const LODOP = getLodop()
  if (!LODOP || !LODOP.PRINT_INIT) {
    Modal.warning({
      title: 'C-Lodop 打印服务异常',
      content: '请检查C-Lodop 打印服务是否开启，开启后刷新页面重试。'
    })
  }
  LODOP.PRINT_INIT('')
  // 乘以10，是因为设置纸张大小的单位是cm, 设计的时候用的mm
  LODOP.SET_PRINT_PAGESIZE(1, canvas.width * 10, (canvas.height * 1 + offsetTop * 1) * 10)
  const ids: any[] = []
  labelList.value.forEach((item: any) => {
    ids.push(item.labelId)
    LODOP.NewPage()
    elements.forEach((el) => {
      const { type } = el
      const size = el.size
      const left = el.left * 0.5 + 'pt',
        top = el.top * 0.5 + offsetTop * 1 + 'pt',
        width = el.width * 0.5 + 'pt',
        height = el.height * 0.5 + 'pt'

      LODOP.SET_PRINT_STYLEA('FontName', '微软雅黑')
      // 文本
      if (type === 'word') {
        LODOP.ADD_PRINT_TEXT(top, left, width, height, el.content)
        LODOP.SET_PRINT_STYLEA(0, 'FontSize', size)
        LODOP.SET_PRINT_STYLEA(0, 'Bold', 1)
      }
      // // 条形码
      if (type === 'barCode') {
        LODOP.ADD_PRINT_BARCODE(top, left, width, height, '128Auto', item.labelNumber || '12345678')
        LODOP.SET_PRINT_STYLEA(0, 'ShowBarText', 0)
      }
      // // 二维码
      if (type === 'qrCode') {
        LODOP.ADD_PRINT_BARCODE(top, left, width, height, 'QRCode', item.labelNumber)
        LODOP.SET_PRINT_STYLEA(0, 'ShowBarText', 0)
      }
      // // 业务字段
      if (type === 'business') {
        const text = item.isTest
          ? setTestBusinessTest(el)
          : setBusinessElementText(el, item.jsonObj || JSON.parse(item.labelJson || '{}'))
        LODOP.ADD_PRINT_TEXT(top, left, width, height, text)
        LODOP.SET_PRINT_STYLEA(0, 'FontSize', size)
        LODOP.SET_PRINT_STYLEA(0, 'Bold', 1)
      }
      LODOP.SET_PRINT_STYLEA(0, 'Stretch', 0)
      LODOP.SET_PRINT_MODE('POS_BASEON_PAPER', 'true')
    })
  })
  // console.log(LODOP)
  // LODOP.PRINT_DESIGN()
  LODOP.PREVIEW()
  /**
   * start 打印后更新一下表格打印次数
   * 为什么要用setTimeout? 因为打印完成后，先会请求更新打印次数的接口，更新完了之后再刷新列表，所以暂时是等2秒
   * 为什么不写在updateLabelPrintCount的回调里面？因为现在配置中心的接口是单独的，不用updateLabelPrintCount方法，避免写两遍代码（后续如果接口统一了，可以移至updateLabelPrintCount）
   */
  setTimeout(() => {
    emits('printSuccess')
  }, 2000)
  /** end */
  const labelIds = labelList.value.map((item) => item.labelId)
  // 使用自定义打印总数记录的函数
  if (props.customPrintTotalFn) {
    props.customPrintTotalFn(labelIds)
    return
  }
  // 如果没有传入模块类型，不做次数记录
  if (!props.moduleType) {
    return
  }
  updateLabelPrintCount({
    labelIds: labelIds,
    moduleType: props.moduleType
  })
}

defineExpose({
  show
})
</script>

<style lang="less">
.label-print-modal.tn-model-full-scroll .ant-modal-content {
  width: 900px;
}
</style>
